import React, { Component } from "react";
import store from "./store";

import {
  changeInputAction,
  addItemAction,
  deleteItemAction,
  getMyListAction,
} from "./store/actionCreators";
import TodoListUI from "./TodoListUI";
class TodoList extends Component {
  constructor(props) {
    super(props);
    this.state = store.getState();
    this.changeInputValue = this.changeInputValue.bind(this);
    this.storeChange = this.storeChange.bind(this);
    this.handleAdd = this.handleAdd.bind(this);
    this.handleRemove = this.handleRemove.bind(this);
  }

  componentDidMount() {
    store.subscribe(this.storeChange);

    // const action = getTodoList();
    // store.dispatch(action);

    const action = getMyListAction();
    store.dispatch(action);
  }
  changeInputValue(e) {
    const value = e.target.value;
    const action = changeInputAction(value);
    store.dispatch(action);
  }
  storeChange() {
    this.setState(store.getState());
  }
  handleAdd() {
    const action = addItemAction();
    store.dispatch(action);
  }
  handleRemove(index) {
    const action = deleteItemAction(index);
    store.dispatch(action);
  }

  render() {
    const { inputValue, list } = this.state;
    return (
      <TodoListUI
        list={list}
        inputValue={inputValue}
        changeInputValue={this.changeInputValue}
        handleAdd={this.handleAdd}
        handleRemove={this.handleRemove}
      />
    );
  }
}

export default TodoList;
